<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomActions.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted } from 'vue'
import { baseURL } from '@/utils/request'
import io, { Socket } from 'socket.io-client'
import { userUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enums/index'
import { ref, nextTick, provide } from 'vue'
import { getconsultOrderItem } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
const store = userUserStore()
const route = useRoute()

const consult = ref<ConsultOrderItem>()
const loadConsult = async () => {
  const res = await getconsultOrderItem(route.query.orderId as string)
  consult.value = res.data
}

//修改评价状态
const completeState = (score: number) => {
  const item = list.value.find((k) => k.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msgType = MsgType.CardEva
    item.msg.evaluateDoc = { score }
  }
}

//跨级别通信
provide('consult', consult)
//传递方法修改数据
provide('completeState', completeState)

//如果是第一次进来则加载数据到最底部
const initdata = ref(true)
const list = ref<Message[]>([])
//在组件创建好后建立连接
let socket: Socket
onMounted(() => {
  loadConsult()
  socket = io(baseURL, {
    //携带token
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  //监听socken连接
  socket.on('connect', () => {
    console.log('连接成功')
  })

  //断开连接
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
  //监听错误
  socket.on('error', (error) => {
    console.log('发生错误: ', error)
  })

  //获取服务器发来的历史消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = []
    data.forEach((item, index) => {
      if (index === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        id: item.createTime,
        createTime: item.createTime
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    loading.value = false
    if (arr.length === 0) return showToast('没有更多记录了')

    if (initdata.value) {
      //将最新消息标为已读
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initdata.value = false
      })
    }
  })

  socket.on('statusChange', () => loadConsult())
  //接收消息
  socket.on('receiveChatMsg', async (event) => {
    socket.emit('updateMsgStatus', event.id)
    list.value.push(event)
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})

//组件卸载关闭连接
onUnmounted(() => {
  socket.close()
})

//接收消息
const onMessage = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
const onImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :count-down="consult?.countdown"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></room-message>
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="onMessage"
      @send-img="onImg"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
